﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;

namespace ExpressTreeDemo
{
    //public delegate int ChangeNumberDelegate(int input);
    public class TestClass
    {
        private int _num;
        //public event ChangeNumberDelegate OnChange;
        public TestClass(int num)
        {
            _num = num;
        }

        public void Change(Expression<Func<int,int>> change)
        {
            //var newexp = Expression.Multiply(change.Body, Expression.Constant(2));
            // var newLambda = Expression.Lambda<Func<int,int>>(newexp,change.Parameters[0]);

            var oldexp = change.Body as BinaryExpression;
            var newexp = Expression.Subtract(oldexp.Left, oldexp.Right);

            var newItem = Expression.New(typeof(Random));
            var callNext = Expression.Call(newItem, "Next", Type.EmptyTypes, newexp, oldexp);
            var newLambda = Expression.Lambda<Func<int, int>>(callNext, change.Parameters[0]);

            var changedNumber = newLambda?.Compile().Invoke(_num);
            _num = changedNumber ?? _num;
        }

        public void Change2(Expression<Func<int, int>> change)
        {
            var oldexp = change.Body as BinaryExpression;

            AddToMinus atm = new AddToMinus();
            var newexp = atm.Change(oldexp);

            var newItem = Expression.New(typeof(Random));
            var callNext = Expression.Call(newItem, "Next", Type.EmptyTypes, newexp, oldexp);
            var newLambda = Expression.Lambda<Func<int, int>>(callNext, change.Parameters[0]);

            var changedNumber = newLambda?.Compile().Invoke(_num);
            _num = changedNumber ?? _num;
        }


        public void Print()
        {
            Console.WriteLine($"num={_num}");
        }
    }
}
